package com.fn.flutter_fn_sdk.page;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.fn.flutter_fn_sdk.PluginDelegate;
import com.fn.flutter_fn_sdk.event.AdEventAction;
import com.fn.sdk.api.banner.FnBannerAd;
import com.fn.sdk.api.banner.FnBannerAdListener;
import com.qq.e.ads.banner2.UnifiedBannerADListener;
import com.qq.e.ads.banner2.UnifiedBannerView;
import com.qq.e.comm.util.AdError;

import java.util.Locale;
import java.util.Map;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.platform.PlatformView;

/**
 * Banner 广告 View
 */
class AdBannerView extends BaseAdPage implements PlatformView, FnBannerAdListener {
    private final String TAG = AdBannerView.class.getSimpleName();
    @NonNull
    private final FrameLayout frameLayout;
    private final PluginDelegate pluginDelegate;
    private int id;
    private FnBannerAd bv;
    private Map<String, Object> params;


    AdBannerView(@NonNull Context context, int id, @Nullable Map<String, Object> creationParams, PluginDelegate pluginDelegate) {
        this.id = id;
        this.pluginDelegate = pluginDelegate;
        this.params = creationParams;
        frameLayout = new FrameLayout(context);
        String posId = (String) params.get(PluginDelegate.KEY_POSID);
        showAd(this.pluginDelegate.activity, posId, null);
    }

    @NonNull
    @Override
    public View getView() {
        return frameLayout;
    }

    @Override
    public void dispose() {
        disposeAd();
    }

    @Override
    public void loadAd(Activity activity, @NonNull MethodCall call) {
        // 加载广告 Banner
        bv = new FnBannerAd();
        bv.loadAd(activity,frameLayout,posId,this);
    }

    /**
     * 销毁广告
     */
    private void disposeAd(){
        frameLayout.removeAllViews();
    }

    @Override
    public void onReceive() {
        Log.i(TAG, "onExposure");
        sendEvent(AdEventAction.onAdLoaded);
    }

    @Override
    public void onExposure() {
        Log.i(TAG, "onExposure");
        sendEvent(AdEventAction.onAdExposure);
    }

    @Override
    public void onClicked() {
        Log.i(TAG, "onClick");
        sendEvent(AdEventAction.onAdClicked);
    }

    @Override
    public void onClosed() {
        Log.i(TAG, "onClose");
        sendEvent(AdEventAction.onAdClosed);
    }

    @Override
    public void onError(int i, String s, String s1) {
        Log.d(TAG, "onError adError:" + i+"s:"+s+"s1:"+s1);
        sendErrorEvent(i, s);
    }
}